import React, { useEffect, useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Button, Form, message, Select, Typography } from 'antd';
import Tables from '@/hoc/Tables';
import styles from './index.less';
import { TASK_LIST } from '@/services/list';
import Models from '@/components/Models';
import { contributionTask, insertCreativeTask, queryByCreaterIdWorks, queryByUserNameEntry, queryCentralizationExhibition, updateCreativeTask } from '@/services/addworks';
import { connect } from 'umi';
import { taskitem } from './index.d';
import { GenericProps, TableProps } from '@/global.d';
import { queryAllExhibition } from '@/services/institution';

const { Option } = Select;

const { Text } = Typography;

const status = ['未投稿', '已投稿'];

const Task: React.FC<GenericProps> = props => {
  const childRef = useRef<TableProps | any>();
  const [form] = Form.useForm();
  let title = props?.route?.name;
  let columns: any[] = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '印面',
      dataIndex: 'printingSurface',
      key: 'printingSurface',
    },
    {
      title: '边款一',
      dataIndex: 'frameA',
      key: 'frameA',
    },
    {
      title: '边款二',
      dataIndex: 'frameB',
      key: 'frameB',
    },
    {
      title: '边款三',
      dataIndex: 'frameC',
      key: 'frameC',
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (_: any, text: any) => <span>{status[text?.state] ?? '--'}</span>,
    },
    {
      title: '操作',
      width: 250,
      render: (text: any) => (
        <div className="operation">
          <span onClick={() => onEdit(text)}>
            <Text>详情</Text>
          </span>
          <span onClick={() => addfn(text)}>
            <Text>编辑</Text>
          </span>
          <span
            onClick={() => {
              if (text?.state == 0) onChange(text);
            }}>
            <Text disabled={text?.state == 1 ? true : false}>投稿</Text>
          </span>
        </div>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const [visible, setVisible] = useState<boolean>(false);
  const [visibles, setVisibles] = useState<boolean>(false);
  const [taskItem, setTaskItem] = useState<taskitem>({
    exhibitionList: [],
    termsList: [],
    id: undefined,
    item: {},
  });
  const [addvisibles, setAddvisibles] = useState<boolean>(false);
  const [optionArr, setOptionArr] = useState<any[]>([]);
  const [bitionList, setbitionList] = useState<any[]>([]);
  const [id, setId] = useState<string | number | null>('');
  const [item, setItem] = useState<any>({});
  const { userData } = props;

  /**
   * 投稿
   */
  const onChange = (text: any): void => {
    setVisible(true);
    setId(text?.id);
  };

  /**
   * 通用弹框关闭
   */
  const handleCancel = () => {
    setVisible(false);
    setVisibles(false);
    setAddvisibles(false);
    form.resetFields();
  };

  /**
   * 详情
   * @param text
   */
  const onEdit = (text: any): void => {
    setVisibles(true);
    setItem(text);
  };

  /**
   * 作品投稿保存
   * @param value
   */
  const onFinish = (value: { workId?: string }) => {
    contributionTask({ id, ...value }).then(res => {
      if (res?.responseCode == 200) {
        message.success('作品投稿成功');
        handleCancel();
        childRef.current.setQuery({});
      }
    });
  };

  /**
   * 初始化投稿数据
   */
  useEffect(() => {
    queryByCreaterIdWorks({ userId: userData?.id }).then(res => {
      if (res?.responseCode == 200) {
        setOptionArr(res?.data);
      }
    });

    queryCentralizationExhibition({ userId: userData?.id }).then(res => {
      if (res?.responseCode == 200) {
        taskItem.exhibitionList = res?.data;
        setTaskItem(() => ({
          ...taskItem,
        }));
      }
    });
    queryByUserNameEntry({ userId: userData?.id }).then(res => {
      if (res?.responseCode == 200) {
        taskItem.termsList = res?.data;
        setTaskItem(() => ({
          ...taskItem,
        }));
      }
    });

    queryAllExhibition().then(res => {
      if (res?.responseCode == 200) {
        setbitionList(res?.data);
      }
    });

    return () => {
      setOptionArr([]);
    };
  }, []);

  /**
   * 新增任务/编辑任务
   */
  const addfn = (text: any) => {
    if (text) {
      taskItem.item = text;
      taskItem.id = text?.id;
      setTaskItem(() => ({ ...taskItem }));
      form.setFieldsValue(text);
    }
    setAddvisibles(true);
  };

  /**
   * 提交
   * @param values
   */
  const onFinish1 = (values: any) => {
    let distributionId: any = null;
    if (values?.entryId) {
      distributionId = taskItem?.termsList?.find(el => el.id == values?.entryId)?.userId;
    }
    let value: any = {
      ...values,
      distributionId: distributionId || userData?.id,
      id: taskItem?.item?.id,
    };

    // 判断是否为编辑
    if (taskItem?.id) {
      updateCreativeTask(value).then(res => {
        if (res?.responseCode == 200) {
          message.success('任务比编辑成功');
          handleCancel();
        }
      });
    } else {
      insertCreativeTask(value).then(res => {
        if (res?.responseCode == 200) {
          message.success('任务添加成功');
          handleCancel();
        }
      });
    }
    childRef.current.setQuery({});
  };

  /**
   * 选择展览名称
   * @param value
   */
  const handleChange = (value: number) => {
    childRef.current.setQuery({ exhibitionId: value, pageIndex: 1 });
  };

  return (
    <div className={styles.regimePage}>
      <PageTitle
        title={title}
        right={
          <Button onClick={addfn} className="btn_red">
            新增任务
          </Button>
        }
      />
      <div className="regime_table">
        <div className="regime_select">
          <Select style={{ width: 300 }} allowClear placeholder="请选择展览名称" onChange={handleChange}>
            {bitionList?.map(el => (
              <Option key={el.exhibitionId + '123131key_id'} value={el.exhibitionId}>
                {el.exhibitionName}
              </Option>
            ))}
          </Select>
        </div>

        <Tables childRef={childRef} url={TASK_LIST} option={{ userId: userData?.id }} columns={columns} />
      </div>
      {/* 详情 */}
      <Models closable={true} className="add_regime text_detail" width="540px" visible={visibles} handleCancel={handleCancel}>
        <div className="body_item">
          <div className="body_title">参展展览</div>
          <div className="body_i">{item?.exhibition}</div>
          <div className="hr"></div>
          <div className="body_title">已选词条</div>
          <div className="body_i">{item?.selectedEntries}</div>
          <div className="regime_btns">
            <Button className="btn_cold" onClick={handleCancel}>
              关闭
            </Button>
          </div>
        </div>
      </Models>

      {/* 投稿 */}
      <Models closable={true} className="add_regime" width="540px" visible={visible} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} name="control-hooks" onFinish={onFinish}>
          <div className="add_user">编辑·创作任务信息</div>
          <Form.Item label="作品名称" name="workId" required={false} rules={[{ required: true, message: '请选择作品名称' }]}>
            <Select size="large" className="regime_input" placeholder="请选择作品名称" allowClear>
              {optionArr?.map((el, index) => (
                <Option key={index + '123123_id_key'} value={el.id}>
                  {el?.printingAnnotations}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <div className="regime_btns">
            <Button className="btn_cold" onClick={handleCancel}>
              取消
            </Button>
            <Button className="btn_red" htmlType="submit">
              提交
            </Button>
          </div>
        </Form>
      </Models>

      {/* 新增/编辑 */}
      <Models closable={true} className="add_regime" width="540px" visible={addvisibles} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} name="control-hooks" onFinish={onFinish1}>
          <div className="add_user">{taskItem?.id ? '编辑任务' : '新增任务'}</div>
          <Form.Item label="展览名称" name="exhibitionId" required={false} rules={[{ required: true, message: '请选择展览名称' }]}>
            <Select size="large" className="regime_input" placeholder="请选择展览名称" allowClear>
              {taskItem?.exhibitionList?.map((el, index) => (
                <Option key={index + '123123_id_key'} value={el.id}>
                  {el?.exhibitionName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="选择词条" name="entryId" required={false}>
            <Select size="large" className="regime_input" placeholder="请选择词条名称" allowClear>
              {taskItem?.termsList?.map((el, index) => {
                return (
                  <Option key={`${index}123123_id_key`} value={el.id}>
                    {el?.id}.{el?.entryName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <div className="regime_btns">
            <Button className="btn_cold" onClick={handleCancel}>
              取消
            </Button>
            <Button className="btn_red" htmlType="submit">
              提交
            </Button>
          </div>
        </Form>
      </Models>
    </div>
  );
};

export default connect(({ login }: { [index: string]: any }) => ({ userData: login.userData }))(Task);
